// $Id: rpsutils.jsm 13 2012-03-01 02:03:34Z hhofer69@gmail.com $

"use strict";

Components.utils.import("resource://gre/modules/Services.jsm");
Components.utils.import("resource://gre/modules/FileUtils.jsm");
Components.utils.import("resource://gre/modules/DownloadLastDir.jsm");  
Components.utils.import("resource://services-sync/main.js");
Components.utils.import("chrome://rpsmodules/content/common/syncutils.jsm");
Components.utils.import("chrome://rpsmodules/content/common/logutils.jsm");

var EXPORTED_SYMBOLS = [ "RequestPolicyBackup", "RpsUtil" ];


//*****************************************************************************
//* Backup / Restore
//*****************************************************************************

const assert = SyncUtil.assert;

var RequestPolicyBackup = {
  OK:        0,
  CANCELLED: 1,
  FAILED:    2,
  
  backup: function STB_backup(sts, file) {
    try {
      let ReqPol = {}
      Components.utils.import("resource://requestpolicy/FileUtil.jsm", ReqPol);
      Components.utils.import("chrome://reqpolsync/content/rpsengine.jsm");

      if (!file) {
        let  maxAge = Services.prefs.getIntPref("extensions.reqpolsync.bakage") * 24 * 3600 * 1000;
        file = SyncUtil.makeBackupFile(ReqPolCache.dbdir, "reqpolsync", ".txt", maxAge);
        if (file.exists()) return this.CANCELLED;
      }
      if (file) {
        if (!file.parent.exists())  file.parent.create(1, 0x700);
        if (file.exists())          file.remove(false);

        // behave like prefWindow.js, but use our cache
        ReqPolCache.refresh();
        let cached = ReqPolCache.items(), types = ReqPolCache.POLICY_TYPES;
        let lines  = [];
        for (let t in types) { // orig, dest, o2d
          lines.push("["+types[t].section+"]");
          Object.keys(cached)
                .filter( function(guid) { return cached[guid].type == t; })
                .forEach(function(guid) { lines.push(cached[guid].value); });
        }
        ReqPol.FileUtil.arrayToFile(lines, file);
        
        Logging.debug("created backup: "+file.path);
        return this.OK;
      }
    } catch (exc) {
      Logging.logException(exc);
    }
    return this.FAILED;
  },
  
  restore: function STB_restore(sts, file) {
    return this.FAILED; // use RequestPolicy's import
  },
  
  firstStart: function STB_firstStart(sts, doBackup) {
    Components.utils.import("chrome://reqpolsync/content/rpsengine.jsm");
    let bakdir = ReqPolCache.dbdir;
    gDownloadLastDir.setFile("chrome://reqpolsync", bakdir);
    if (!bakdir.exists()) bakdir.create(1, 0x700);
    if (doBackup) {
      let f = bakdir.clone();
      f.append("reqpolsync-firstrun.txt");
      this.backup(sts, f);
    }
  },
};

var RpsUtil = {
  getContents: function RPU_getContents(aURL) {
    // from http://forums.mozillazine.org/viewtopic.php?p=921150#921150
    
    // !!!! This locks the .xpi if the aURL is a chrome:// or resource://
    
    let ioService = Components.classes["@mozilla.org/network/io-service;1"]
                              .getService(Components.interfaces.nsIIOService);
    let scriptableStream = Components.classes["@mozilla.org/scriptableinputstream;1"]
                                     .getService(Components.interfaces.nsIScriptableInputStream);

    let channel = ioService.newChannel(aURL,null,null);
    let input   = channel.open();
    scriptableStream.init(input);
    let str = scriptableStream.read(input.available());
    scriptableStream.close();
    input.close();
    channel.cancel(42);
    return str;
  }
  // <DevRelease>
  ,

  showDebugInfo: function RPU_showDebugInfo() {
    Components.utils.import("chrome://reqpolsync/content/rpsengine.jsm");

    let cache = ReqPolCache.items(), rp = ReqPolCache.jsreqpol;
    let keys  = Object.keys(cache);
    let info  = "Cache Size: "+keys.length+"\n", rpinfo = "";
    for (let t in ReqPolCache.POLICY_TYPES)
      info += "  "+t+": "+keys.filter(function(k) cache[k].type == t).length+"\n";
    let rpt = 0, RP = { _allowedOrigins: "orig", _allowedDestinations: "dest", _allowedOriginsToDestinations: "o2dt"};
    for (let r in RP) {
      rpt    += Object.keys(rp[r]).length
      rpinfo += "  "+RP[r]+": "+Object.keys(rp[r]).length+"\n";
    }
    info += "RequestPolicy: "+rpt+"\n"+rpinfo;
    info += "Cache DB: "+ReqPolCache.db.getCount()+"\n";
    Services.prompt.alert(null, "reqpolsync debug", info);
  },
  // </DevRelease>
};

//*****************************************************************************
//* Logging
//*****************************************************************************
Logging.CATEGORY     = "reqpolsync";
Logging.PFX          = Logging.CATEGORY+": ";
Logging.DEBUG        = Services.prefs.getBoolPref("extensions.reqpolsync.debug");
Logging.LOGFILE_PREF = "extensions.reqpolsync.logfile";

SyncUtil.setLogging(Logging);
